class FilledSurvey < ActiveRecord::Base
	include AliasingColumns
        
	set_table_name "FILLED_SURVEYS"  
	AliasingColumns.add_aliases columns
		
	has_many :oqanswers,
			 :class_name => "OQAnswer",
			 :foreign_key => "filled_survey_id",	   
			 :dependent => :destroy
	
	has_many :cqanswers,
			 :class_name => "CQAnswer",
			 :foreign_key => "filled_survey_id",	   
			 :dependent => :destroy
			 
			 		 
	belongs_to :survey,
			   :class_name => "Survey",
			   :foreign_key => "survey_id"
			   
	belongs_to :user,
			   :class_name => "User",
			   :foreign_key => "user_id"
	accepts_nested_attributes_for :oqanswers, :allow_destroy => true	
			   		 
	validate :answers_within_limits		   
	
	def answers_within_limits
		
	
		if !(self.new_record?) && ready=='y'
			
			for cqquestion in survey.closed_questions 
				min=cqquestion.closedquestion.min_answers
				max=cqquestion.closedquestion.max_answers
				existing_answers=0
				for possible in cqquestion.closedquestion.cqpossibleanswers
					existing_answers+=possible.cqanswers.find(:all,:conditions=>"filled_survey_id=#{self.id}" ).length
			
				end
				STDERR.puts(min.to_s<<"_______"<<max.to_s<<"_______"<<existing_answers.to_s)
				if existing_answers>max|| existing_answers<min
					errors.add_to_base("Ankieta nie może być oznaczona jako gotowa - liczba udzielonych odpowiedzi w pytaniu:\n '#{cqquestion.question}' jest nieprawidłowa.")
						#STDERR.puts "xxxxxxxxxxxxxxx"
					
				end
			
			end
		end
		
	end
	
	
	def inv_validate 
		self.validate
	end
	if  AliasingColumns.get_adapter_name == "oracle"
#		self.primary_key ="ID"
		set_sequence_name table_name()<<"_SEQ" 
	#	before_create :set_id
		def set_id
			 self.ID =connection.next_sequence_value(self.class.sequence_name)	
		end 
	end
	
	
				 
	
end
